<script setup>
import {ref, onMounted, watch} from 'vue';
import {useRoute} from "vue-router";
import {getChapterInfoReq, getContentReq} from "@/api/chapter.js";
import router from "@/router/router.js";
import {ElLoading} from "element-plus";

//从路径state中获取url
const route = useRoute();
const url = ref(route.query.url || '');

const loadingInstance = ref(null);//加载

const info = ref({
    title:'',//标题
    content:'',//内容
    preChapterUrl:'',//上一章地址
    nextChapterUrl:'',//下一章地址
    chapterDir:''//章节目录

})

//显示文章内容
const showContent = async (url) => {
    loadingInstance.value = ElLoading.service({ fullscreen: true, text: '加载中...' });
    try {
        var result = await getContentReq(url);
        info.value = result.data
    } catch (error) {
        console.error('请求失败:', error);
    } finally {
        loadingInstance.value.close();
      // 滚动到顶部
      const contentElement = document.querySelector('.content');
      if (contentElement) {
        contentElement.scrollTop = 0;
      }

    }
}

//回到目录界面
const backDir = (url) => {
    console.log(url);
    router.push({ path: `/webFictionInfo`, query: { titleUrl: url } });
};

onMounted(() => {
    showContent(url.value)
});

// 监听查询参数变化
watch(() => route.query.url, (newUrl) => {
    if (newUrl) {
        url.value = newUrl;
        showContent(url.value); // 更新内容
    }
});
</script>

<template>
    <el-card class="card-container">
        <template #header>
            <div class="card-header">
                <h1>{{info.title}}</h1>
            </div>
        </template>

        <!-- 文章内容 -->
        <div class="content" v-html="info.content"></div>

        <template #footer>
            <div class="links">
                <a href="javascript:void(0)" @click="showContent(info.preChapterUrl)">
                    上一章
                </a>
                <a href="javascript:void(0)" @click="backDir(info.chapterDir)">
                    章节目录
                </a>
                <a href="javascript:void(0)" @click="showContent(info.nextChapterUrl)">
                    下一章
                </a>
            </div>
        </template>
    </el-card>

</template>

<style scoped>
.card-header {
    display: flex;
    flex-direction: column;
    align-items: center; /* Center horizontally */
    text-align: center; /* Center text inside the header */
  height: auto;
  box-sizing: border-box;
}

.card-header h1 {
    margin: 0;
    font-size: 1.5rem;
    position: relative;
}

.links {
    display: flex;
    justify-content: center; /* Center links horizontally */
    gap: 30px; /* Spacing between links */
}

.content{
    position: sticky;
    max-height: 70vh;
    overflow-y: scroll;
}
</style>
